package com.zeng.sim.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zeng.sim.controller.domain.SimMsgRecord;
import com.zeng.sim.controller.domain.msg.MsgData;
import com.zeng.sim.controller.domain.request.PageDomain;
import com.zeng.sim.mapper.model.SimMsgRecordEntity;
import com.zeng.sim.service.ClientMsgService;
import com.zeng.sim.service.SimMsgRecordService;
import com.zeng.sim.support.protocol.IMsgProtocol;
import com.zeng.sim.support.protocol.MsgProtocolFactory;
import com.zeng.sim.util.MsgUtil;
import com.zeng.sim.util.SimConstant;
import com.zeng.sim.util.SysConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 描述信息
 *
 * @author zengwanlin
 * @date 2023-12-21T15:17
 */
@Service
public class ClientMsgServiceImpl implements ClientMsgService {

    private Logger logger = LoggerFactory.getLogger(ClientMsgServiceImpl.class);

    @Autowired
    private SimMsgRecordService simMsgRecordService;

    @Resource(name = "busiPoolExecutor")
    private ThreadPoolExecutor busiPoolExecutor;

    /**
     * 发送消息
     * @param msgData
     * @param protocol
     */
    @Override
    public String sendMsg(MsgData msgData, SimConstant.MsgProtocol protocol) {
        msgData.setMsgContent(HtmlUtils.htmlUnescape(msgData.getMsgContent()));
        IMsgProtocol msgProtocol = MsgProtocolFactory.getMsgProtocol(protocol);
        return msgProtocol.sendMsg(msgData);
    }

    /**
     * 客户端报文列表查询
     * @param msgRecord
     * @param pageDomain
     * @return
     */
    @Override
    public Page<SimMsgRecord> data(SimMsgRecord msgRecord, PageDomain pageDomain) {
        Page page = Page.of(pageDomain.getPage(), pageDomain.getLimit());
        LambdaQueryWrapper<SimMsgRecordEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SimMsgRecordEntity::getBusiType, SimConstant.BUSI_TYPE_01);
        if (StringUtils.hasLength(msgRecord.getChannelNo())) {
            wrapper.eq(SimMsgRecordEntity::getChannelNo, msgRecord.getChannelNo());
        }
        if (StringUtils.hasLength(msgRecord.getMsgCode())) {
            wrapper.eq(SimMsgRecordEntity::getMsgCode, msgRecord.getMsgCode());
        }
        if (StringUtils.hasLength(msgRecord.getMsgName())) {
            wrapper.like(SimMsgRecordEntity::getMsgName, msgRecord.getMsgName());
        }
        simMsgRecordService.page(page, wrapper);

        List<SimMsgRecordEntity> recordList = page.getRecords();
        List<SimMsgRecord> list = new ArrayList<>(recordList.size());
        for (SimMsgRecordEntity msgRecordEntity : recordList) {
            SimMsgRecord simMsgRecord = new SimMsgRecord();
            BeanUtils.copyProperties(msgRecordEntity, simMsgRecord);
            simMsgRecord.setMsgContent(null);
            list.add(simMsgRecord);
        }
        page.setRecords(list);

        return page;
    }

    /**
     * 批量发送报文（作为客户端）
     * @param idList
     */
    @Override
    public void batchSend(List<Integer> idList) {
        for (Integer id : idList) {
            SimMsgRecordEntity msgRecordEntity = simMsgRecordService.getById(id);
            busiPoolExecutor.execute(() -> {
                MsgData msgData = new MsgData();
                msgData.setHostname(
                        SysConfigUtil.getSystemConfigValue(SysConfigUtil.CONFIG_CODE_CLIENT_SIM_SERVER_HOSTNAME));
                msgData.setPort(Integer
                    .parseInt(SysConfigUtil.getSystemConfigValue(SysConfigUtil.CONFIG_CODE_CLIENT_SIM_SERVER_PORT)));
                msgData.setCharsetName(msgRecordEntity.getCharsetName());
                msgData.setMsgContent(msgRecordEntity.getMsgContent());
                msgData.setHeadStrategy(msgRecordEntity.getHeadStrategy());

                msgData.setUrl(SysConfigUtil.getSystemConfigValue(SysConfigUtil.CONFIG_CODE_CLIENT_SIM_SERVER_URL));
                if (MsgUtil.isJson(msgRecordEntity.getMsgContent())) {
                    msgData.setMediaType(MediaType.APPLICATION_JSON_VALUE);
                }
                else if (MsgUtil.isXml(msgRecordEntity.getMsgContent())) {
                    msgData.setMediaType(MediaType.APPLICATION_XML_VALUE);
                }
                else {
                    msgData.setMediaType(MediaType.TEXT_PLAIN_VALUE);
                }
                msgData.setHttpMethod(msgRecordEntity.getHttpMethod());
                sendMsg(msgData, SimConstant.MsgProtocol.getInstance(msgRecordEntity.getProtocol()));
            });
        }
    }

}
